package eu.testing.system.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import eu.testing.system.dao.AnswerDao;
import eu.testing.system.models.Answer;

public class AnswerDaoImpl extends SimpleJdbcDaoSupport implements AnswerDao {
	private static final String SQL_INSERT = "INSERT INTO answer (USERNAME,TEST_ID, QUESTION_ID,ID, TRUTH) VALUES (?, ?, ?, ?,?)";
	private static final String SQL_SELECT = "SELECT * FROM answer WHERE USERNAME = ? AND TEST_ID = ? and ID = ?";
	private static final String SQL_UPDATE = "UPDATE answer SET USERNAME = ?, TEST_ID = ?, QUESTION_ID = ?, ID= ?, TRUTH = ? WHERE TEST_ID = ?";

	@Override
	public void insertAnswer(Answer answer) {
		getJdbcTemplate().update(SQL_INSERT, answer.getUsername(),
				answer.getTestId(), answer.getQuestionId(), answer.getId(),
				answer.isTruth());
	}

	@Override
	public void editAnswer(Answer answer) {
		getJdbcTemplate().update(SQL_UPDATE, answer.getUsername(),
				answer.getTestId(), answer.getQuestionId(), answer.getId(),
				answer.isTruth());

	}

	@Override
	public Answer getAnswer(String username, int testId, int id) {
		return getSimpleJdbcTemplate().queryForObject(SQL_SELECT,
				new AnswerParameterizedRowMapper(), username, testId, id);

	}

	public class AnswerParameterizedRowMapper implements
			ParameterizedRowMapper<Answer> {
		@Override
		public Answer mapRow(ResultSet rs, int rowNum) throws SQLException {
			Answer answer = new Answer();
			answer.setUsername(rs.getString("USERNAME"));
			answer.setTestId(rs.getInt("TEST_ID"));
			answer.setQuestionId(rs.getInt("QUESTION_ID"));
			answer.setId(rs.getInt("ID"));
			answer.setTruth(rs.getBoolean("TRUTH"));
			return answer;
		}

	}

}
